package com.jacoco.incremental.utils;


import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * jacoco 命令
 */

public class JacocoCMD {


    private StringBuilder message = new StringBuilder();

    /**
     * 执行命令
     *
     * @param order
     * @return
     * @throws Exception
     */
    public boolean exec(String[] order, File file) throws Exception {
        boolean success = true;
        ProcessBuilder builder = new ProcessBuilder(order);
//        builder.redirectErrorStream(true);
        if (file != null) builder.directory(file);

        Process p = builder.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        p.waitFor(60L, TimeUnit.SECONDS);

        String line = "";
        while ((line = reader.readLine()) != null) {
//            message.append(line + "\n");
            System.out.println(line);
        }
        if (p.exitValue() != 0) { //执行失败
            success = false;
            ViewInfo.error("执行失败: " + getProcess(order));
        }
        p.destroy();
        return success;
    }

    private String getProcess(String[] order) {
        StringBuilder builder = new StringBuilder();
        for (String k : order) {
            builder.append(k).append(" ");
        }
        return builder.toString();
    }

    public boolean exec(String[] order) throws Exception {
        return exec(order, null);
    }

    private String arrayToString(String[] array) {
        if (Empty.isNotEmpty(array)) {
            StringBuilder builder = new StringBuilder();
            for (String t : array) {
                builder.append(t + " ");
            }
            return builder.toString();
        }
        return "";
    }

    public static void main(String[] args) {
        BufferedReader reader;
        Process process = null;
//        File file = new File("/Users/chunlonghuang/IdeaProjects/jacoco/source");
        String[] cmd = {"ant -f /Users/chunlonghuang/IdeaProjects/jacoco/source/build.xml report"};
        try {
            for (String c : cmd) {
                if (Empty.isEmpty(c)) continue;
                process = new ProcessBuilder(c.split(" "))
//                        .directory(file)
                        .start();
                reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
                process.waitFor(120L, TimeUnit.SECONDS);
            }
        } catch (IOException e) {
        } catch (InterruptedException e) {
        } finally {
            process.destroy();
        }
    }
}
